﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Identity;
using TomNet.IMSC.Model.DbModels.Identity;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;
using TomNet.Utility.Extensions;
using TomNet.IMSC.Web.Filters;

namespace TomNet.IMSC.Web.Areas.Identity.Controllers
{
	[Description("管理-角色管理")]
	[GlobalAuthorization]
	public class RoleController : BaseController
    {
		public IRoleContract RoleContract { get; set; }
		public IAuthorityContract AuthorityContract { get; set; } 
        public IAuthorityGroupContract AuthorityGroupContract { get; set; }
        public IRoleAuthorityContract RoleAuthorityContract { get; set; }

        #region ActionResult Index()

        [Description("管理-角色列表")]
		public ActionResult Index()
		{
			return View();
		}

		#endregion

		#region ActionResult IndexAsync(int pageIndex, int pageSize, string keyWord = "")

		[Description("管理-角色列表")]
		[HttpPost, AjaxOnly, NotCollected]
		public ActionResult IndexAsync(int pageIndex, int pageSize, string keyWord = "")
		{
			var query = RoleContract.Entities.Where(p => (keyWord == "" || p.Name.Contains(keyWord)) ).Select(a => new
			{
				Id = a.Id,
				Name = a.Name,
				Remark = a.Remark,
			});

			//数据总数
			var total = query.Count();

			//默认给一个排序的字段
			query = query.OrderBy(m => m.Id);

			//分页(假如total == 0，则取消分页查询，提高性能)
			query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);

			//此处可以采用匿名对象 GridData<object>
			GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

			//此处采用重写后的jsonResult
			return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
		}

		#endregion

		#region ActionResult Insert()

		[Description("管理-角色添加")]
		public ActionResult Insert()
		{
			//权限
			List<Authority> infosAuth = AuthorityContract.Entities.ToList();
			ViewData["auth"] = infosAuth;

			return View();
		}

		#endregion

		#region ActionResult InsertAsync(Role entity)

		[Description("管理-角色添加")]
		[HttpPost, AjaxOnly, NotCollected]
		public ActionResult InsertAsync(Role entity)
		{
			//所有AJAX的结果，返回统一数据格式
			var result = new AjaxResult();
			try
			{
				var query = RoleContract.CheckExists(m => m.Name.Equals(entity.Name));
				if (query)
				{
					result.Type = AjaxResultType.Error;
					result.Content = "已经存在相同的信息";
				}
				else
				{
                    //entity.AuthorityIds = Request.Form["AuthorityId"];

					var count = RoleContract.Insert(entity);
					if (count > 0)
					{
						result.Type = AjaxResultType.Success;
						result.Content = "录入成功";
					}
					else
					{
						result.Type = AjaxResultType.Error;
						result.Content = "录入失败";
					}
				}
			}
			catch
			{
				result.Type = AjaxResultType.Error;
				result.Content = "异常操作";
			}
			return JsonEx(result);
		}

		#endregion

		#region ActionResult Edit(int id)

		[Description("管理-角色修改")]
		public ActionResult Edit(int id)
		{
			var entity = RoleContract.GetByKey(id);

			//后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
			if (entity == null) throw new Exception("未找到该实体"); 

			ViewData["entity"] = entity;
			return View();
		}

		#endregion

		#region ActionResult EditAsync(Role entity)

		[Description("管理-角色修改")]
		[HttpPost, AjaxOnly, NotCollected]
		public ActionResult EditAsync(Role entity)
		{
			var result = new AjaxResult();
			try
			{
				var query = RoleContract.CheckExists(m => m.Name.Equals(entity.Name) && m.Id != entity.Id);
				if (query)
				{
					result.Type = AjaxResultType.Error;
					result.Content = "已经存在相同的信息";
				}
				else
				{
					//entity.AuthorityIds = Request.Form["AuthorityId"];

					var count = RoleContract.Update(entity);
					if (count > 0)
					{
						result.Type = AjaxResultType.Success;
						result.Content = "修改成功";
					}
					else
					{
						result.Type = AjaxResultType.Error;
						result.Content = "修改失败";
					}
				}
			}
			catch
			{
				result.Type = AjaxResultType.Error;
				result.Content = "异常操作";
			}
			return JsonEx(result);
		}

		#endregion

		#region ActionResult DeleteAsync(string ids)

		[Description("管理-角色删除")]
		[HttpPost, AjaxOnly]
		public ActionResult DeleteAsync(string ids)
		{
			var result = new AjaxResult();
			try
			{
				string[] idsStr = ids.Split(new char[] { ',' });
				int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                RoleContract.DeleteDirect(m => idsInt.Contains(m.Id));

				result.Type = AjaxResultType.Success;
				result.Content = "删除成功";
			}
			catch
			{
				result.Type = AjaxResultType.Error;
				result.Content = "异常操作";
			}
			return JsonEx(result);
		}

        #endregion
        #region 权限
        public ActionResult Jurisdiction(int id)
        {
            var One = AuthorityGroupContract.Entities.Where(m => m.Id == 1).FirstOrDefault();
            var Tow = AuthorityGroupContract.Entities.Where(m => m.Id == 2).FirstOrDefault();
            var Three = AuthorityGroupContract.Entities.Where(m => m.Id == 3).FirstOrDefault();
            var Four = AuthorityGroupContract.Entities.Where(m => m.Id == 4).FirstOrDefault();
            var Five = AuthorityGroupContract.Entities.Where(m => m.Id == 5).FirstOrDefault();
            var Six = AuthorityGroupContract.Entities.Where(m => m.Id == 6).FirstOrDefault();
            ViewBag.One = One.Name;
            ViewBag.Tow = Tow.Name;
            ViewBag.Three = Three.Name;
            ViewBag.Four = Four.Name;
            ViewBag.Five = Five.Name;
            ViewBag.Six = Six.Name;
            var entity = RoleAuthorityContract.Entities.Where(m => m.RoleID == id).ToList();
            ViewBag.entity = entity;
            ViewBag.RoleID = id;


            Inner();
            return View();
        }
        #endregion

        #region 权限添加
        public ActionResult JurisdictionAsync(RoleAuthority entity)
        {
            var result = new AjaxResult();
            var AuthorityID = Request["authorityid"];
            if (AuthorityID == null)
            {
                try
                {

                    RoleAuthorityContract.Repository.UnitOfWork.BeginTransaction();
                    //删除原有权限 
                    var DeleteEntity = RoleAuthorityContract.Entities.Where(m => m.RoleID == entity.RoleID).ToList();
                    for (int o = 0; o < DeleteEntity.Count(); o++)
                    {
                        RoleAuthorityContract.Delete(DeleteEntity[o].Id);
                    }
                    RoleAuthorityContract.Repository.UnitOfWork.Commit();

                }
                catch (Exception)
                {
                    RoleAuthorityContract.Repository.UnitOfWork.Rollback();
                    throw;
                }
                result.Type = AjaxResultType.Success;
                result.Content = "添加成功";
            }
            else
            {
                var authorityid = AuthorityID.Split(',');
                var count = 0;
                try
                {
                    RoleAuthorityContract.Repository.UnitOfWork.BeginTransaction();
                    //删除原有权限 
                    var DeleteEntity = RoleAuthorityContract.Entities.Where(m => m.RoleID == entity.RoleID).ToList();
                    //var a = DeleteEntity
                    for (int o = 0; o < DeleteEntity.Count(); o++)
                    {
                        RoleAuthorityContract.DeleteDirect(DeleteEntity[o].Id);
                    }

                    for (int i = 0; i < authorityid.Length; i++)
                    {
                        entity.AuthorityID = Convert.ToInt32(authorityid[i]);
                        count = RoleAuthorityContract.Insert(entity);
                    }
                    RoleAuthorityContract.Repository.UnitOfWork.Commit();
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "添加成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "添加失败";
                    }
                }
                catch
                {
                    RoleAuthorityContract.Repository.UnitOfWork.Rollback();
                    result.Type = AjaxResultType.Error;
                    result.Content = "异常操作";
                }
            }
            return JsonEx(result);
        }
        #endregion

        #region 菜单与权限
        public void Inner()
        {
            //编号1基础菜单0
            List<SelectListItem> GridData = new List<SelectListItem>();
            var OneEntityZero = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 1 && a.IsMenu == 0
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(OneEntityZero);
            ViewBag.OneEntityZero = new SelectList(GridData);
            //编号1基础权限1
            GridData = new List<SelectListItem>();
            var OneEntityOne = from ag in AuthorityGroupContract.Entities
                               join a in AuthorityContract.Entities
                               on ag.Id equals a.AuthorityGroupID
                               where ag.Id == 1 && a.IsMenu == 1
                               select new SelectListItem
                               {
                                   Value = a.Id + "",
                                   Text = a.Name
                               };
            GridData.AddRange(OneEntityOne);
            ViewBag.OneEntityOne = new SelectList(GridData);
            //编号2新房菜单0
            GridData = new List<SelectListItem>();
            var TowEntityZero = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 2 && a.IsMenu == 0
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(TowEntityZero);
            ViewBag.TowEntityZero = new SelectList(GridData);
            //编号2新房权限1
            GridData = new List<SelectListItem>();
            var TowEntityOne = from ag in AuthorityGroupContract.Entities
                               join a in AuthorityContract.Entities
                               on ag.Id equals a.AuthorityGroupID
                               where ag.Id == 2 && a.IsMenu == 1
                               select new SelectListItem
                               {
                                   Value = a.Id + "",
                                   Text = a.Name
                               };
            GridData.AddRange(TowEntityOne);
            ViewBag.TowEntityOne = new SelectList(GridData);
            //编号3低价房菜单0
            GridData = new List<SelectListItem>();
            var ThreeEntityZero = from ag in AuthorityGroupContract.Entities
                                  join a in AuthorityContract.Entities
                                  on ag.Id equals a.AuthorityGroupID
                                  where ag.Id == 3 && a.IsMenu == 0
                                  select new SelectListItem
                                  {
                                      Value = a.Id + "",
                                      Text = a.Name
                                  };
            GridData.AddRange(ThreeEntityZero);
            ViewBag.ThreeEntityZero = new SelectList(GridData);
            //编号3低价房权限1
            GridData = new List<SelectListItem>();
            var ThreeEntityOne = from ag in AuthorityGroupContract.Entities
                                 join a in AuthorityContract.Entities
                                 on ag.Id equals a.AuthorityGroupID
                                 where ag.Id == 3 && a.IsMenu == 1
                                 select new SelectListItem
                                 {
                                     Value = a.Id + "",
                                     Text = a.Name
                                 };
            GridData.AddRange(ThreeEntityOne);
            ViewBag.ThreeEntityOne = new SelectList(GridData);
            //编号4二手房菜单0
            GridData = new List<SelectListItem>();
            var FourEntityZero = from ag in AuthorityGroupContract.Entities
                                 join a in AuthorityContract.Entities
                                 on ag.Id equals a.AuthorityGroupID
                                 where ag.Id == 4 && a.IsMenu == 0
                                 select new SelectListItem
                                 {
                                     Value = a.Id + "",
                                     Text = a.Name
                                 };
            GridData.AddRange(FourEntityZero);
            ViewBag.FourEntityZero = new SelectList(GridData);
            //编号4二手房权限1
            GridData = new List<SelectListItem>();
            var FourEntityOne = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 4 && a.IsMenu == 1
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(FourEntityOne);
            ViewBag.FourEntityOne = new SelectList(GridData);
            //编号5装修菜单0
            GridData = new List<SelectListItem>();
            var FiveEntityZero = from ag in AuthorityGroupContract.Entities
                                 join a in AuthorityContract.Entities
                                 on ag.Id equals a.AuthorityGroupID
                                 where ag.Id == 5 && a.IsMenu == 0
                                 select new SelectListItem
                                 {
                                     Value = a.Id + "",
                                     Text = a.Name
                                 };
            GridData.AddRange(FiveEntityZero);
            ViewBag.FiveEntityZero = new SelectList(GridData);
            //编号5装修权限1
            GridData = new List<SelectListItem>();
            var FiveEntityOne = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 5 && a.IsMenu == 1
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(FiveEntityOne);
            ViewBag.FiveEntityOne = new SelectList(GridData);
            //编号6金融菜单0
            GridData = new List<SelectListItem>();
            var SixEntityZero = from ag in AuthorityGroupContract.Entities
                                join a in AuthorityContract.Entities
                                on ag.Id equals a.AuthorityGroupID
                                where ag.Id == 6 && a.IsMenu == 0
                                select new SelectListItem
                                {
                                    Value = a.Id + "",
                                    Text = a.Name
                                };
            GridData.AddRange(SixEntityZero);
            ViewBag.SixEntityZero = new SelectList(GridData);
            //编号6金融权限1
            GridData = new List<SelectListItem>();
            var SixEntityOne = from ag in AuthorityGroupContract.Entities
                               join a in AuthorityContract.Entities
                               on ag.Id equals a.AuthorityGroupID
                               where ag.Id == 6 && a.IsMenu == 1
                               select new SelectListItem
                               {
                                   Value = a.Id + "",
                                   Text = a.Name
                               };
            GridData.AddRange(SixEntityOne);
            ViewBag.SixEntityOne = new SelectList(GridData);
        }
        #endregion
    }
}